<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoProvider.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoAddress.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoFavourite.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoRating.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoUpdate.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoResource.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/favourite.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/resource.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/sendMail.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/parameters.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/generalFunctions.php';

class ProviderBus {
	private $_userBus;	
	private $_providerDao;
	private $_addressDao;
	private $_favouriteDao;
	private $_ratingDao;
	private $_updateDao;
	
	//constructor
	public function __construct() {
		$this->_userBus = new UserBus();
		$this->_providerDao = new ProviderDao();
		$this->_addressDao = new AddressDao();
		$this->_favouriteDao = new FavouriteDao();
		$this->_ratingDao = new RatingDao();
		$this->_updateDao = new UpdateDao();		
	}
	
	public function addProvider($provider) {
		$provider->setAnswerList(GeneralFunctions::stripString($provider->getAnswerList()));
		$provider->setCategoryList(GeneralFunctions::stripString($provider->getCategoryList()));
		$provider->setCellphone(GeneralFunctions::stripString($provider->getCellphone()));
		$provider->setProvider(GeneralFunctions::stripString($provider->getProvider()));
		$provider->setResourceList(GeneralFunctions::stripString($provider->getResourceList()));
		$provider->setTelephone(GeneralFunctions::stripString($provider->getTelephone()));
		$provider->setWebsite(GeneralFunctions::stripString($provider->getWebsite()));
		$provider->setEmail(GeneralFunctions::stripString($provider->getEmail()));
		
		$currentTime = $_SERVER['REQUEST_TIME'];

		$provider->setCreatedDate($currentTime);
		$provider->setAccessedDate($currentTime);
		$provider->setModifiedDate($currentTime);
		
		$id = $this->_providerDao->addProvider($provider);
		if ($id) {
			global $ubi_score;
			$this->_userBus->addScore($provider->getUserID(), $ubi_score['ONE_POST']);
			
			$update = new UpdateModel();
			$update->setIndicteeID($itemID);
			$update->setModifiedDate($currentTime);
			$update->setUpdateType($ubi['UPDATE']['POST_PROVIDER']);
			$update->setUserID($userID);
			$update->setLink('index.php?view&type=provider&id=' . $providerID);
			$update->setName($provider->getProvider());
			
			$this->_updateDao->addUpdate($update);
		}
		
		return $id;
	}
	
	public function getProvider($providerID) {
		return $this->_providerDao->getProvider($providerID);
	}
	
	//get a list of providers by user id
	//returns an array of providers record
	public function getProvidersByUserID($userID) {
		return $this->_providerDao->getProvidersByUserId($userID);
	}
	
	public function getProvidersByUserIDOfPage($userID, $page) {
		global $ubi;
		$from = ($page - 1) * $ubi['SITE']['USER_NUMBER_POST'];
		$offset = $ubi['SITE']['USER_NUMBER_POST'];
		
		return $this->_providerDao->getProvidersByUserIDFromTo($userID, $from, $offset);
	}
	
	//public function getNumberOfProvidersByUserId($user)
	//get number of providers by user id
	//returns number of provider of the user
	public function getNumberOfProvidersByUserID($userID) {
		return $this->_providerDao->getNumberOfProvidersByUserID($userID);
	}
	
	public function addResource($provider, $resourceID) {
		$id = $this->_providerDao->addResource($provider, $resourceID);
		if ($id) {
			global $ubi_score;
			$this->_userBus->addScore($provider->getUserID(), $ubi_score['UPLOAD_PIC']);
		}
		return $id;
	}	
		
	public function searchProviders($searchText) {
		return $this->_providerDao->searchProvider($searchText);	
	}
	
	public function searchAdvancedProviders($city, $district, $ward, $number, $street, $providerName, $page) {
		global $ubi;
		$from = $page * $ubi['SITE']['N_POSTS_PER_PAGE'];
		
		if (isset($city) && isset($district) && isset($ward) && isset($number) && isset($street) && isset($providerName)) {
			return $this->_providerDao->searchAdvancedProviders($city, $district, $ward, $number, $street, $providerName, $from, $ubi['SITE']['N_POSTS_PER_PAGE']);
		} else {
			return $this->_providerDao->searchProvidersByRegion($city, $ubi['LOCATION']['PROVIDER'], $from, $ubi['SITE']['N_POSTS_PER_PAGE']);
		}
	}
	
	public function getSearchProviderByXML($searchText) {		
		if (!is_numeric($searchText)) {
			$arrProvider = $this->_providerDao->searchProvider($searchText);
		} else {
			$arrProvider = array();
			$arrProvider[] = $this->_providerDao->getProvider($searchText);
		}
		if (count($arrProvider) > 0) {
			$xml = "<Providers>";
			
			foreach ($arrProvider as $provider) {
				$xml .= "<Provider id='" . $provider->getProviderID() . "' name='" . $provider->getProvider() 
				. "' address='" . $this->_addressDao->getAddressString($provider->getAddressID()) . "' />";
			}
			
			$xml .= "</Providers>";
			
			return $xml;
		}
	}
	
	public function getLike($providerID, $userID) {		
		$isLike = $this->_providerDao->isLike($itemID, $userID);
		$isUnLike = $this->_providerDao->isUnLike($itemID, $userID);
				
		$getLike = 0;
		if ($isLike) {
			$getLike = 1;
		}
		if ($isUnLike) {
			$getLike = -1;
		}	
		
		return $getLike;
	}
	
	public function isFavourite($providerID, $userID) {
		global $ubi;
		
		return $this->_favouriteDao->isFavourite($userID, $ubi['PROVIDER']['VALUE'], $providerID);
	}
	
	public function isPlus($providerID, $userID) {
		global $ubi;
		
		$rating = new RatingModel();
		$rating->setCreatedDate($_SERVER['REQUEST_TIME']);
		$rating->setIndicteeID($providerID);
		$rating->setInteractType($ubi['PROVIDER']['VALUE']);
		$rating->setRatingValue($ubi['RATING']['PLUS']);
		$rating->setUserID($userID);
		
		return $this->_ratingDao->isRating($rating);
	}
	
	public function isMinus($providerID, $userID) {
		global $ubi;
		
		$rating = new RatingModel();
		$rating->setCreatedDate($_SERVER['REQUEST_TIME']);
		$rating->setIndicteeID($providerID);
		$rating->setInteractType($ubi['PROVIDER']['VALUE']);
		$rating->setRatingValue($ubi['RATING']['MINUS']);
		$rating->setUserID($userID);
		
		return $this->_ratingDao->isRating($rating);
	}
	
	public function plus($providerID, $userID) {
		global $ubi;

		$rating = new RatingModel();
		$rating->setCreatedDate($_SERVER['REQUEST_TIME']);
		$rating->setIndicteeID($providerID);
		$rating->setInteractType($ubi['PROVIDER']['VALUE']);
		$rating->setRatingValue($ubi['RATING']['PLUS']);
		$rating->setUserID($userID);
		
		$ck = $this->_ratingDao->doRateProvider($rating);

		if ($ck) {
			// add update
			$update = new UpdateModel();
			$update->setIndicteeID($providerID);
			$update->setModifiedDate($rating->getCreatedDate());
			$update->setUpdateType($ubi['UPDATE']['PLUS_PROVIDER']);
			$update->setUserID($userID);
			$update->setLink('index.php?view&type=provider&id=' . $itemID);
			$update->setName($this->_providerDao->getProvider($providerID)->getProvider());
			
			$this->_updateDao->addUpdate($update);			
			
			// send mail for the owner
			$post = $this->_providerDao->getProvider($providerID);
			$ownerPost = $this->_userBus->getUser($post->getUserID());
			if (!in_array($ubi['EMAIL']['PLUS_MY_POST'], $ownerPost->getEmailPrivacies())) {
				$sender = $this->_userBus->getUser($userID);
				SendMail::getEmailTemplate($ubi['EMAIL']['PLUS_MY_POST'], $template, $subject);
				
				$arrParam = array();
				$arrParam[] = $ownerPost->getFirstName() . ' ' . $ownerPost->getLastName();	
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . 'index.php?view&type=user&userid=' . $sender->getUserID() . '">' . $sender->getUserName() . '</a>';
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . 'index.php?view&type=provider&id=' . $post->getProviderID() . '">' . $post->getProvider() . '</a>';
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . '">' . $ubi['SERVER']['SITE_NAME'] . '</a>';
				SendMail::sendEMail($template, $subject, $arrParam, $ownerPost->getEmail());
			}
			
			// add score
			global $ubi_score;
			$this->_userBus->addScore($userID, $ubi_score['PLUS_MINUS']);
		}
		
		return $ck;
				
	}
	
	public function minus($providerID, $userID) {
		global $ubi;

		$currentTime = $_SERVER['REQUEST_TIME'];
		$rating = new RatingModel();
		$rating->setCreatedDate($currentTime);
		$rating->setIndicteeID($providerID);
		$rating->setInteractType($ubi['PROVIDER']['VALUE']);
		$rating->setRatingValue($ubi['RATING']['MINUS']);
		$rating->setUserID($userID);
		
		$ck = $this->_ratingDao->doRateProvider($rating);

		if ($ck) {
			// add update
			$update = new UpdateModel();
			$update->setIndicteeID($providerID);
			$update->setModifiedDate($currentTime);
			$update->setUpdateType($ubi['UPDATE']['MINUS_PROVIDER']);
			$update->setUserID($userID);
			$update->setLink('index.php?view&type=provider&id=' . $providerID);
			$update->setName($this->_providerDao->getProvider($providerID)->getProvider());
			
			$this->_updateDao->addUpdate($update);			
			
			// send mail for the owner
			$post = $this->_providerDao->getProvider($providerID);
			$ownerPost = $this->_userBus->getUser($post->getUserID());
			if (!in_array($ubi['EMAIL']['MINUS_MY_POST'], $ownerPost->getEmailPrivacies())) {
				$sender = $this->_userBus->getUser($userID);
				SendMail::getEmailTemplate($ubi['EMAIL']['MINUS_MY_POST'], $template, $subject);
				
				$arrParam = array();
				$arrParam[] = $ownerPost->getFirstName() . ' ' . $ownerPost->getLastName();	
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . 'index.php?view&type=user&userid=' . $sender->getUserID() . '">' . $sender->getUserName() . '</a>';
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . 'index.php?view&type=provider&id=' . $post->getProviderID() . '">' . $post->getProvider() . '</a>';
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . '">' . $ubi['SERVER']['SITE_NAME'] . '</a>';
				SendMail::sendEMail($template, $subject, $arrParam, $ownerPost->getEmail());
			}
			
			// add score
			global $ubi_score;
			$this->_userBus->addScore($userID, $ubi_score['PLUS_MINUS']);
		}
		
		return $ck;
	}
	
	public function favourite($providerID, $userID) {
		global $ubi;

		$fav = new FavouriteModel();
		$fav->setCreatedDate($_SERVER['REQUEST_TIME']);
		$fav->setIndicteeID($providerID);
		$fav->setInteractType($ubi['PROVIDER']['VALUE']);
		$fav->setUserID($userID);
		
		$ck = $this->_favouriteDao->addFavourite($fav);

		if ($ck) {
			//add update
			$update = new UpdateModel();
			$update->setIndicteeID($providerID);
			$update->setModifiedDate($fav->getCreatedDate());
			$update->setUpdateType($ubi['UPDATE']['FAVOURITE_PROVIDER']);
			$update->setUserID($userID);
			$update->setLink('index.php?view&type=provider&id=' . $providerID);
			$update->setName($this->_providerDao->getProvider($providerID)->getProvider());
			
			$this->_updateDao->addUpdate($update);
			
			// send mail for the owner
			$post = $this->_providerDao->getProvider($providerID);
			$ownerPost = $this->_userBus->getUser($post->getUserID());
			if (!in_array($ubi['EMAIL']['FAVOURITE_MY_POST'], $ownerPost->getEmailPrivacies())) {
				$sender = $this->_userBus->getUser($userID);
				SendMail::getEmailTemplate($ubi['EMAIL']['FAVOURITE_MY_POST'], $template, $subject);
				
				$arrParam = array();
				$arrParam[] = $ownerPost->getFirstName() . ' ' . $ownerPost->getLastName();	
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . 'index.php?view&type=user&userid=' . $sender->getUserID() . '">' . $sender->getUserName() . '</a>';
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . 'index.php?view&type=provider&id=' . $post->getProviderID() . '">' . $post->getProvider() . '</a>';
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . '">' . $ubi['SERVER']['SITE_NAME'] . '</a>';
				SendMail::sendEMail($template, $subject, $arrParam, $ownerPost->getEmail());
			}
			
			// add score for user favourite a post			
			global $ubi_score;
			$this->_userBus->addScore($userID, $ubi_score['FAVOURITE_POST']);
		}
		
		return $ck;
	}
	
	public function removeFavourite($providerID, $userID) {
		global $ubi;

		$fav = new FavouriteModel();		
		$fav->setIndicteeID($providerID);
		$fav->setInteractType($ubi['PROVIDER']['VALUE']);
		$fav->setUserID($userID);
		
		$ck = $this->_favouriteDao->removeFavourite($fav);

		if ($ck) {
			// add update
			$update = new UpdateModel();
			$update->setIndicteeID($providerID);
			$update->setModifiedDate($_SERVER['REQUEST_TIME']);
			$update->setUpdateType($ubi['UPDATE']['REMOVE_FAVOURITE_PROVIDER']);
			$update->setUserID($userID);
			$update->setLink('index.php?view&type=provider&id=' . $providerID);
			$update->setName($this->_providerDao->getProvider($providerID)->getProvider());
			
			$this->_updateDao->addUpdate($update);
			
			// send email
			$post = $this->_providerDao->getProvider($providerID);
			$ownerPost = $this->_userBus->getUser($post->getUserID());
			if (!in_array($ubi['EMAIL']['UNFAVOURITE_MY_POST'], $ownerPost->getEmailPrivacies())) {
				$sender = $this->_userBus->getUser($userID);
				SendMail::getEmailTemplate($ubi['EMAIL']['UNFAVOURITE_MY_POST'], $template, $subject);
				
				$arrParam = array();
				$arrParam[] = $ownerPost->getFirstName() . ' ' . $ownerPost->getLastName();	
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . 'index.php?view&type=user&userid=' . $sender->getUserID() . '">' . $sender->getUserName() . '</a>';
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . 'index.php?view&type=provider&id=' . $post->getProviderID() . '">' . $post->getProvider() . '</a>';
				$arrParam[] = '<a href="' . $ubi['SERVER']['SITE_ROOT'] . '">' . $ubi['SERVER']['SITE_NAME'] . '</a>';
				SendMail::sendEMail($template, $subject, $arrParam, $ownerPost->getEmail());
			}
		}
		
		return $ck;
	}	
	
	public function getListImgs($listProvider) {
		global $ubi;
		
		$imgs = array();
		$resBus = new ResourceBus();
		
		foreach ($listProvider as $provider) {
			$resID = GeneralFunctions::getFirstElement($provider->getResourceList());
			if ($resID !== false) {
				$img = $resBus->getImgOfResource($resID);
				$imgs[$provider->getProviderID()] = $img; 
			} else {
				$imgs[$provider->getProviderID()] = $ubi['PROVIDER']['DEFAULT_RESOURCE'];
			}		
		}
		
		return $imgs;
	}
	
	public function updateProvider($provider) {
		$provider->setModifiedDate($_SERVER['REQUEST_TIME']);
		$provider->setAnswerList(GeneralFunctions::stripString($provider->getAnswerList()));
		$provider->setCategoryList(GeneralFunctions::stripString($provider->getCategoryList()));
		$provider->setCellphone(GeneralFunctions::stripString($provider->getCellphone()));
		$provider->setProvider(GeneralFunctions::stripString($provider->getProvider()));
		$provider->setResourceList(GeneralFunctions::stripString($provider->getResourceList()));
		$provider->setTelephone(GeneralFunctions::stripString($provider->getTelephone()));
		$provider->setWebsite(GeneralFunctions::stripString($provider->getWebsite()));
		
		return $this->_providerDao->updateProvider($provider);
	}
	
	public function incFrequency($providerID) {
		$this->_providerDao->incFrequency($providerID);
	}
	
	public function getNumberOfComment($providerID) {
		return $this->_providerDao->getNumberOfComments($providerID);
	}
	
	public function getNumberOfFavourites($providerID) {
		return $this->_providerDao->getNumberOfFavourites($providerID);
	}
	
	public function getProviderMaxFrequency() {
		return $this->_providerDao->getProviderMaxFrequency();
	}
	
	public function getNewestProviders() {
		return $this->_providerDao->getNewestProviders();	
	}
	
	public function getRandomProviders() {
		global $ubi;
		
		$providers = $this->_providerDao->getRandomProviders($ubi['SITE']['NUMBER_N_RANDOM']);
		
		return $providers;
	}	
	
	public function updateMapImage($providerID) {
		global $ubi;
		
		$provider = $this->_providerDao->getProvider($providerID);
		do {
			$mapFileName = "Map" . GeneralFunctions::createRandomCode() . ".jpg";
			$newFileName = $ubi['SERVER']['SERVER_ROOT'] . '/' . $ubi['SERVER']['RESOURCE_PATH'] . '/' . $mapFileName;
		} while (file_exists($newFileName));

		$addressModel = $this->_addressDao->getAddress($provider->getAddressID());
		$addrStr = $addressModel->getNumber() . ", " . $addressModel->getStreet() . ", " . $addressModel->getDistrict() . ", " . $addressModel->getCity() . ", " . "Vietnam";
		$addrStr = urlencode($addrStr);
		$urlSite = "http://maps.google.com/maps/api/staticmap?zoom=15&size=317x350&markers=color:blue%7Clabel:S%7C" . $addrStr . "&sensor=true&format=jpg";
		
		GeneralFunctions::get_file($urlSite, $newFileName);

		$resourceDao = new ResourceDao();
		$res = new ResourceModel();
		$res->setResourceName($mapFileName);
		$res->setShortDescription('map');
		$mapResID = $resourceDao->addResource($res);
		
		$this->_providerDao->updateUrlImage($providerID, $mapResID);
		
		return $mapFileName;
	}
	
	public function findProviderDTOsByLocationID($locationID) {
		return $this->_providerDao->findProviderDTOsByLocationID($locationID);
	}
}
?>